var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
var util = require('util');
 var fs = require('fs');
 var sql = require('../sql.js');
router.use('/', function(req, res){

    var form = new multiparty.Form({uploadDir: './public/photo/'});   
    form.parse(req, function (err, filed, files) {       
        var filesTmp = JSON.stringify(files,null,2);
          
        if(err) {
           console.log(err)
        }
        else  {   
            var id=req.cookies.id;                
            var inputFile=files.upload[0];
            var uploadedPath = inputFile.path;
            let fileFormat = (inputFile.originalFilename).split('.') // 取后缀
            let fileName=new Date().getTime()+ id + '.' + fileFormat[fileFormat.length - 1]
            var dstPath = './public/photo/' + fileName;
           
            console.log(fileFormat)
            fs.rename(uploadedPath, dstPath, function(err) {
                if(err){
                  console.log('rename error: ' + err);
                } else {
                  console.log('rename ok');
                  var mypath = dstPath.replace("./public","http://localhost"+":3000"); //context.ip是我自己设置的后台的ip名，根据环境，可以是localhost,也可以是电脑ip
                  console.log(typeof mypath)
                  res.send({errno:0,data:[mypath]}) //返回图片路径，让前端展示                  
                 
              
                }
              });

        } 
    })
  
   
});
module.exports = router; 